package com.xiong.wuliao;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.xiong.wuliao.entity.GoodSpecial;
import com.xiong.wuliao.util.GoodSepcialJSON;

import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品详情页面（单品页面点击进来的页面）
 */
public class GoodActivity extends AppCompatActivity implements View.OnClickListener {
    // 所有商品详情的地址前段,后面跟传过来的ID
    private String GoodsPath = "http://api.wuliaoribao.com/v2/items/";
    // 详细的商品对象的ID
    private String myGoodID;
    // 商品详情数据对象
    private GoodSpecial goodSpecial;
    // 顶部图片轮播ViewPager
    private ViewPager myGoodViewPager;
    // 图片轮播的图片列表
    private List<String> myGoodPic;
    // 图片轮播的适配器
    private MyViewPagerAdapter adapter;
    // 顶部标题
    private TextView myGoodTextViewName;
    // 顶部价钱
    private TextView myGoodTextViewPrice;
    // 顶部介绍
    private TextView myGoodTextViewDescription;

    // 商品详情网页
    private WebView myGoodWebView;
    // 返回图片按钮
    private ImageButton myButtonGoodBack;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good);
        init();
    }

    private void init() {
        findView();
        getGood();
        initData();
        setListener();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getGoodSpecialServerData();
    }

    /**
     * 拿到传过来的商品对象ID
     */
    private void getGood() {
        Intent intent = getIntent();
        myGoodID = intent.getStringExtra("good");

    }

    /**
     * 设置监听事件
     */
    private void setListener() {
        myButtonGoodBack.setOnClickListener(this);
    }

    /**
     * 获取服务器数据
     */
    private void getGoodSpecialServerData(){
        String string = GoodsPath+myGoodID;
        OkHttpUtils.get(string).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                goodSpecial = GoodSepcialJSON.saveGoodSpecialData(s.trim());
                handler.sendEmptyMessage(100);
            }
        });
    }

    /**
     * 因为网络请求是个异步任务，所以要在异步任务执行完之后才开始执行
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            setTop();
            setWebView();
        }
    };

    /**
     * 设置网页顶部的标题，价钱，商品介绍等信息
     */
    private void setTop(){
        myGoodTextViewName.setText(goodSpecial.getName());
        myGoodTextViewPrice.setText("$"+goodSpecial.getPrice());
        myGoodTextViewDescription.setText(goodSpecial.getDescription());

        // 获取图片列表
        myGoodPic = goodSpecial.getImage_urls();

        adapter = new MyViewPagerAdapter(GoodActivity.this);
        myGoodViewPager.setAdapter(adapter);
        // 实现图片轮播
        changeCurrent();

        adapter.notifyDataSetChanged();

    }

    /**
     * 调用改变图片的方法
     */
    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            changeCurrent();
        }
    };

    /**
     * 开启一个子线程开改变ViewPager显示的图片
     */
    private void changeCurrent() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            int newIndex = myGoodViewPager.getCurrentItem() + 1;
                            myGoodViewPager.setCurrentItem(newIndex);
                            handler1.sendEmptyMessage(100);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 设置商品详情网页
     */
    private void setWebView() {
        WebSettings setting = myGoodWebView.getSettings();
        setting.setAppCacheEnabled(true);
        setting.setJavaScriptEnabled(true);
        setting.setSupportZoom(true);

        // 获取网页地址
        //myGoodWebView.loadUrl(myGood.getUrl());
        String htmlStr = goodSpecial.getDetail_html();
        myGoodWebView.loadDataWithBaseURL(null,htmlStr,"text/html","utf-8",null);

        // 显示网页
        myGoodWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        // 加载网页
        myGoodWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    /**
     * 初始化控件
     */
    private void findView() {

        myButtonGoodBack = (ImageButton) findViewById(R.id.myButtonGoodBack);
        myGoodWebView = (WebView) findViewById(R.id.goodWebView);
        // 顶部图片轮播ViewPager
        myGoodViewPager = (ViewPager) findViewById(R.id.myGoodSpecialViewPager);
        // 顶部标题
        myGoodTextViewName = (TextView) findViewById(R.id.myGoodSpecialName);
        // 顶部价钱
        myGoodTextViewPrice = (TextView) findViewById(R.id.myGoodSpecialPrice);
        // 顶部介绍
        myGoodTextViewDescription = (TextView) findViewById(R.id.myGoodSpecialDescription);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.myButtonGoodBack:    // 点击返回图标
                GoodActivity.this.finish();
                break;
        }
    }

    /**
     * 广告图片轮训适配器
     */
    private class MyViewPagerAdapter extends PagerAdapter {
        Context context;

        public MyViewPagerAdapter(Context context) {
            this.context = context;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Picasso.with(context).load(myGoodPic.get(position % myGoodPic.size())).placeholder(R.mipmap.shiliimage01).into(imageView);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }
}
